package cn.zzuli.myanimationdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class FrameAnimActivity extends AppCompatActivity {
    private ImageView imageView;
    private AnimationDrawable animationDrawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frame_anim);

        imageView = findViewById(R.id.imageView);
        animationDrawable = (AnimationDrawable) imageView.getBackground();
    }

    public void startAnim(View view) {
        animationDrawable.start();
    }

    public void endAnim(View view) {
        animationDrawable.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != animationDrawable && animationDrawable.isRunning()) {
            animationDrawable.stop();
        }

    }

    public void runFrame(View view) {
        Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.frame1);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int pieceWidth = width / 8;
        int pieceHeight = height;
        //完全编码实现的动画效果
        AnimationDrawable anim = new AnimationDrawable();
        for (int i = 0; i < 8; i++) {
            int xValue = i * pieceWidth;
            int yValue = 0;
            Bitmap bitmap1 = Bitmap.createBitmap(bitmap, xValue, yValue,
                            pieceWidth, pieceHeight);
            BitmapDrawable drawable=new BitmapDrawable(getResources(),bitmap1);
            //将此帧添加到AnimationDrawable中
            anim.addFrame(drawable, 300);
        }
        anim.setOneShot(false); //设置为loop
        imageView.setBackground(anim); //将动画设置为ImageView背景
        anim.start();  //开始动画
    }
}